package com.abigdreamer.im.server.ui.desktop;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;

import javax.swing.JDesktopPane;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;

import com.abigdreamer.im.server.tools.ServerUtils;
import com.abigdreamer.im.server.ui.PropetryTree;
import com.abigdreamer.im.server.ui.desktop.internal.PropertyFrame;
import com.abigdreamer.im.server.ui.resourse.ResourseMannager;

public class EIMDesktop extends JDesktopPane implements MouseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static EIMDesktop instance;

	private Image wallPaper;
	private DeskTopConfig deskTopConfig;
	private JPopupMenu pop = null; // 弹出菜单
	private JMenuItem newItem = null, property = null, refresh = null; // 三个功能菜单
	private static int num = 0;

	public static EIMDesktop getInstance() {
		if (instance == null) {
			instance = new EIMDesktop();
		}
		return instance;
	}

	private EIMDesktop() {
		this.addMouseListener(this);
		deskTopConfig = ServerUtils.getDeskTopConfig();
		initDeskTop(deskTopConfig);
		intWallPaper(deskTopConfig.getWallPaper());
	}

	/**
	 * 初始化桌面背景
	 */
	public void intWallPaper(String wall) {
		this.wallPaper = ResourseMannager.getImage(wall);
		MediaTracker tracker = new MediaTracker(this);
		tracker.addImage(wallPaper, 0);
		try {
			tracker.waitForAll();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化桌面图标 它为xml配置的，可以用反射机制来扩展
	 */
	private void initDeskTop(DeskTopConfig config) {
		pop = creatPopupMenu();
		List<ItemConfig> itemList = config.getItemList();
		for (int i = 0; i < itemList.size(); i++) {
			ItemConfig itemfig = itemList.get(i);
			String itemClass = itemfig.getItemClass();
			try {
				EIMDesktopItem item = (EIMDesktopItem) Class.forName(itemClass).newInstance();
				item.setDesktop(this);
				item.initConfig(itemfig);
				num = i + 1;
				this.add(item, num);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	public void refresh(DeskTopConfig config) {
		this.removeAll();
		num = 0;
		List<ItemConfig> itemList = config.getItemList();
		for (int i = 0; i < itemList.size(); i++) {
			ItemConfig itemfig = itemList.get(i);
			String itemClass = itemfig.getItemClass();
			try {
				EIMDesktopItem item = (EIMDesktopItem) Class.forName(itemClass).newInstance();
				item.setDesktop(this);
				item.initConfig(itemfig);
				num = i + 1;
				this.add(item, num);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private JPopupMenu creatPopupMenu() {
		JPopupMenu pop = new JPopupMenu();
		pop.add(newItem = new JMenuItem("新建"));
		pop.add(new JSeparator());
		pop.add(refresh = new JMenuItem("刷新"));
		pop.add(new JSeparator());
		pop.add(property = new JMenuItem("属性"));

		newItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				menuAction(e);
			}
		});
		refresh.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				menuAction(e);
			}
		});

		property.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				menuAction(e);
			}
		});
		return pop;
	}

	public void menuAction(ActionEvent e) {
		String str = e.getActionCommand();
		if (str.equals(newItem.getText())) {
			num += 1;
			NewDeskTopItem newItem = new NewDeskTopItem();
			newItem.setDesktop(this);
			this.add(newItem, num);
			deskTopConfig.getItemList().add(newItem.getCofig());
			PropetryTree.getInstance(deskTopConfig).refresh();
			ServerUtils.writeDeskTopConfig(deskTopConfig);
		} else if (str.equals(refresh.getText())) {
			this.repaint();
		} else if (str.equals(property.getText())) {
			PropertyFrame propertyFrame = PropertyFrame.getInstance();
			this.remove(propertyFrame);
			this.repaint();
			this.add(propertyFrame);
			propertyFrame.show();
		}
	}

	/**
	 * 
	 * @param item
	 * @param num
	 *            由左向右，由上向下 的位置 ， 比如 9*3 的位置就是27(第三列最后一个)
	 */
	private void add(EIMDesktopItem item, int num) {
		int arranges = deskTopConfig.getArranges();
		int itemRightExcursion = deskTopConfig.getItemRightExcursion();
		int itemDownExcursion = deskTopConfig.getItemDownExcursion();
		int itemWeigth = deskTopConfig.getItemWeigth();
		int itemHigth = deskTopConfig.getItemHigth();

		int row = 0;
		int arry = num % arranges;
		if (arry == 0) {
			row = num / arranges;
			arry = arranges;
		} else {
			row = num / arranges + 1;
		}
		int x = 20 + (row - 1) * itemRightExcursion;
		int y = 20 + (arry - 1) * itemDownExcursion;
		item.setBounds(x, y, itemWeigth, itemHigth);
		this.add(item);

	}

	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		int width = wallPaper.getWidth(this);
		int height = wallPaper.getHeight(this);
		Dimension size = getSize();
		for (int x = 0; x < size.width; x += width)
			for (int y = 0; y < size.height; y += height)
				g.drawImage(wallPaper, x, y, this);
	}

	public Dimension getPreferredSize() {
		return new Dimension(wallPaper.getWidth(this), wallPaper.getHeight(this));
	}

	public void mouseClicked(MouseEvent e) {
		if (e.getButton() == MouseEvent.BUTTON3) {
			pop.show(this, e.getX(), e.getY());
		}
	}

	public void mouseEntered(MouseEvent e) {

	}

	public void mouseExited(MouseEvent e) {

	}

	public void mousePressed(MouseEvent e) {

	}

	public void mouseReleased(MouseEvent e) {

	}

	public DeskTopConfig getDeskTopConfig() {
		return deskTopConfig;
	}

	public void setDeskTopConfig(DeskTopConfig deskTopConfig) {
		this.deskTopConfig = deskTopConfig;
	}

	public static int getNum() {
		return num;
	}

	public static void setNum(int num) {
		EIMDesktop.num = num;
	}
}
